﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Account;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfaces;
using B.S.BasicData.Infrastructure.Utils;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.CommandHandler.Account
{
    public class DelAccountHandler : IRequestHandler<DelAccountCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<AccountModel> accountRepo;  //仓储
        private readonly IMapper mapper; //mapper
        private readonly ILogger<DelAccountHandler> logger; //日志





        //注入--构造函数
        public DelAccountHandler(IBaseRepository<AccountModel> accountRepo, IMapper mapper, ILogger<DelAccountHandler> logger)
        {
            this.accountRepo = accountRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 中介者-账号删除处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(DelAccountCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var model = accountRepo.GetModel(request.Id).Result; //先根据命令里的Id查到要删除的实体对象  .Result
            model.IsDeleted = true;

           var r =  accountRepo.UpdateAsync(model).Result;

            if (r > 0)
            {
                result.Code = ApiEnums.UpdateAccountOk;
                result.Msg = ApiEnums.UpdateAccountOk.Descrption();
                result.Data = r;
            }
            else
            {
                result.Code = ApiEnums.Fail;
                result.Msg = ApiEnums.Fail.Descrption();
                result.Data = r;
            }

           return Task.FromResult(result);
        }
    }
}
